package com.qf.cloud2203.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Component
public class TokenFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        final ServerHttpRequest request = exchange.getRequest();

        System.out.println(request.getPath());

        if (request.getPath().toString().startsWith("/sss")) {
            // 放行该请求
            return chain.filter(exchange);
        }

        // 检查请求头中是否有token
        final HttpHeaders headers = request.getHeaders();
        System.out.println(headers);
        final String token = request.getHeaders().getFirst("token");

        if (token == null){

            final ServerHttpResponse response = exchange.getResponse();


            String msg = "token error";

            DataBuffer wrap =null;
            try {
                wrap = response.bufferFactory().wrap(msg.getBytes("utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            // 向调用方写回数据需要准备 一个 DataBuffer对象，传入下面的方法中
            return response.writeWith(Mono.just(wrap));

        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
